package com.atqh.logistics.controller.Manager;

import cn.hutool.core.date.DateTime;
import com.atqh.logistics.Aop.LogAnnotation;
import com.atqh.logistics.domin.Car;
import com.atqh.logistics.domin.Driver;
import com.atqh.logistics.domin.Mission;
import com.atqh.logistics.mapper.CarMapper;
import com.atqh.logistics.mapper.DriverMapper;
import com.atqh.logistics.mapper.MissionMapper;
import com.atqh.logistics.service.DriverService;
import com.atqh.logistics.service.ManagerService;
import com.atqh.logistics.service.MissionService;
import com.atqh.logistics.service.impl.ManagerServiceImpl;
import com.atqh.logistics.utils.ErrorCode;
import com.atqh.logistics.utils.Result;
import com.atqh.logistics.utils.Vo.MissionAndCustom;
import com.atqh.logistics.utils.Vo.params.CarParam;
import com.atqh.logistics.utils.Vo.params.DriverParam;
import com.atqh.logistics.utils.Vo.params.LoginParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @作者：大叔azhe
 * @api：详细描述
 * @创建时间：19:05 2023/4/11
 * 注意区别两个包下的BeanUtils.copyProperties的区别
 * 1.两个参数位置相反
 * 2.当被拷贝的源参数多于target时，应选用org.springframework.beans.BeanUtils
 * 3.两个包下的都不会覆盖多余的参数
 * 4.都属于浅拷贝（即被拷贝后的对象与新对象指向同一个类），一个改变，另一个也改变
 */
@Api(tags = "管理员最全功能模块")
@RestController
@CrossOrigin
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private MissionService missionService;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private MissionMapper missionMapper;
    private static final String salt = "lum!@#";

    public boolean IsAllRight(int missionid) {

        Mission mission = missionMapper.SelectTargetMission(missionid);
        if (mission != null)
            return true;
        return false;
    }

    @ApiOperation("管理员新增司机")
    @RequestMapping("/savedriver")
    @LogAnnotation(module = "管理员模块", operator = "新增司机")
    public Result saveDriver(@RequestBody DriverParam driverParam) {
        Driver driver = new Driver();
        BeanUtils.copyProperties(driverParam, driver);
        driver.setIsDelete(0);
        driver.setIsUsed(0);
        driver.setPassword(DigestUtils.md5Hex(driverParam.getPassword() + salt));
        int insert = driverMapper.insert(driver);
        if (insert != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        return Result.success(driver);

    }

    @ApiOperation("管理员新增车辆")
    @RequestMapping("/savecar")
    @LogAnnotation(module = "管理员模块", operator = "新增车辆")
    public Result saveCar(@RequestBody CarParam carParam) {
        Car car = new Car();
        BeanUtils.copyProperties(carParam, car);
        car.setIsDeleted(0);
        car.setIsUsed(0);
        car.setCreateTime(new DateTime());
        car.setUpdateTime(new DateTime());
        int insert = carMapper.insert(car);
        if (insert != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        return Result.success(car);

    }

    @ApiOperation("管理员接受或拒绝任务")
    @RequestMapping("/contask/{mid}/{flag}")
    @LogAnnotation(module = "管理员模块", operator = "接受或拒绝任务")
    public Result ControllTask(@PathVariable("mid") int id, @PathVariable("flag") int flag) {
        Mission mission = new Mission();
        mission.setFlag(flag);
        LambdaQueryWrapper<Mission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Mission::getId, id);
        int insert = missionMapper.update(mission, queryWrapper);
        if (insert != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        return Result.success(id);

    }

    @ApiOperation("管理员点击确定按钮为所有接受的任务分配车辆")
    @RequestMapping("/concar/{mid}/{cid}")
    @LogAnnotation(module = "管理员模块", operator = "分配车辆")
    @Transactional
    public Result ControllCar(@PathVariable("mid") int missionid, @PathVariable("cid") int carid) {
        Mission mission = new Mission();
        mission.setCarId(carid);
        LambdaQueryWrapper<Mission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Mission::getId, missionid);
        int insert = missionMapper.update(mission, queryWrapper);
        if (insert != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        Car car = new Car();
        car.setIsUsed(1);
        LambdaQueryWrapper<Car> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Car::getId, carid);
        int update = carMapper.update(car, queryWrapper1);
        if (update == -1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        if (IsAllRight(missionid)) {
            Mission mission1 = new Mission();
            mission1.setSituation(0);
            LambdaQueryWrapper<Mission> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Mission::getId, missionid);
            int update1 = missionMapper.update(mission1, queryWrapper2);
            if (update1 == -1)
                return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        return Result.success(missionid);

    }

    @ApiOperation("管理员点击确定按钮为所有接受的任务分配司机")
    @RequestMapping("/condriver/{mid}/{did}")
    @LogAnnotation(module = "管理员模块", operator = "分配司机")
    @Transactional
    public Result ControllDriver(@PathVariable("mid") int missionid, @PathVariable("did") int driverId) {
        Mission mission = new Mission();
        mission.setDriverId(driverId);
        LambdaQueryWrapper<Mission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Mission::getId, missionid);
        int insert = missionMapper.update(mission, queryWrapper);
        if (insert != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        Driver driver = new Driver();
        driver.setIsUsed(1);
        LambdaQueryWrapper<Driver> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Driver::getId, driverId);
        int update = driverMapper.update(driver, queryWrapper1);
        if (update != 1)
            return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        if (IsAllRight(missionid)) {
            Mission mission1 = new Mission();
            mission1.setSituation(0);
            LambdaQueryWrapper<Mission> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Mission::getId, missionid);
            int update1 = missionMapper.update(mission1, queryWrapper2);
            if (update1 == -1)
                return Result.Fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        return Result.success(missionid);

    }

    @ApiOperation("管理员点击分配司机按钮，查找没有任务的司机（同时判断是否需要司机有危险品资格证）")
    @RequestMapping("/finddriver/{mid}")
    @LogAnnotation(module = "管理员模块", operator = "查找有危险品资格证的司机")
    public Result FindDriver(@PathVariable("mid") int mid) {
        Mission mission = missionMapper.selectById(mid);
        List<Driver> drivers = null;
        if (mission.getIsDanger() == 1) {
            LambdaQueryWrapper<Driver> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Driver::getHasDanger, 1).eq(Driver::getIsUsed, 0);
            drivers = driverMapper.selectList(queryWrapper);
        } else {
            LambdaQueryWrapper<Driver> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Driver::getIsUsed, 0);
            drivers = driverMapper.selectList(queryWrapper);
        }
        return Result.success(drivers);
    }

    @ApiOperation("管理员点击分配车辆按钮，查找没有任务的车辆")
    @RequestMapping("/findcar")
    @LogAnnotation(module = "管理员模块", operator = "查找没有任务的车辆")
    public Result FindCar() {
        List<Car> cars = null;
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Car::getIsUsed, 0);
        cars = carMapper.selectList(queryWrapper);
        return Result.success(cars);
    }


    @ApiOperation("查找当前正在进行的任务")
    @RequestMapping("/findtask")
    @LogAnnotation(module = "管理员模块", operator = "查找当前正在进行的任务")
    public Result FindTask() {
        LambdaQueryWrapper<Mission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Mission::getSituation, 0);
        List<Mission> missions = missionMapper.selectList(queryWrapper);
        return Result.success(missions);

    }

    @ApiOperation("查找当前已完成的任务")
    @RequestMapping("/findcomtask")
    @LogAnnotation(module = "管理员模块", operator = "查找当前已完成的任务")
    public Result FindComTask() {

        List<Mission> missions = missionService.selectComList();
        return Result.success(missions);

    }

    @ApiOperation("查找当前待审核的任务")
    @RequestMapping("/finddaitask")
    @LogAnnotation(module = "管理员模块", operator = "查找当前待审核的任务")
    public Result FindDaiTask() {

        List<MissionAndCustom> missions = missionService.selectDaiList();
        return Result.success(missions);

    }

    @ApiOperation("查找当前待分配车辆和司机的任务")
    @RequestMapping("/findcardrivertask")
    @LogAnnotation(module = "管理员模块", operator = "查找当前待分配车辆和司机的任务")
    public Result FindDaiCarDriverTask() {

        List<Mission> missions = missionService.selectDaiCarDriverList();
        return Result.success(missions);

    }

}